<template>
  <div id="knowledgeTests">
    <div class="searchButtonDiv">
      <vxe-input v-model="searchValue"></vxe-input>
      <vxe-select v-model="searchType" transfer>
        <vxe-option v-for="item in searchQuestionTypeList" :key="item.code" :value="item.code" :label="item.name"></vxe-option>
      </vxe-select>

      <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="查询" @click="findTestQuestionList()"></vxe-button>
      <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新增" @click="handleAddTest()" v-if="!onlyShow"></vxe-button>
    </div>

    <div class="tabTableBox">
      <vxe-table :data="testQuestionList" :loading="isLoading" class="mytable-scrollbar" height="auto" align="left">
        <vxe-column type="seq" title="序号" width="50"></vxe-column>
        <vxe-column field="questionType" title="题目类型" width="120">
          <template #default="{ row }">
            <span>{{ formatQuestionType(row) }}</span>
          </template>
        </vxe-column>
        <vxe-column field="questionContent" title="题目标题" max-width="500"> </vxe-column>

        <vxe-column title="操作" fixed="right" width="100">
          <template #default="{ row, rowIndex }">
            <vxe-button type="text" status="primary" icon="vxe-icon-eye-fill" circle @click.native="handleEditTest(row)" class="spanIcon" v-if="onlyShow"></vxe-button>
            <vxe-button type="text" status="primary" icon="vxe-icon-edit" circle @click.native="handleEditTest(row)" class="spanIcon" v-if="!onlyShow"></vxe-button>
            <vxe-button type="text" status="danger" icon="vxe-icon-delete" circle @click.native="handleDeleteTest(row)" class="spanIcon" v-if="!onlyShow"></vxe-button>
          </template>
        </vxe-column>
      </vxe-table>
    </div>

    <el-dialog title="考试试题" :show-close="false" v-model="showAddTestQuestionDialog" append-to-body :close-on-click-modal="false" width="800px">
      <el-form ref="testQuestionFormRef" :model="testQuestionForm" :rules="TestQuestionFormRules" label-width="100px" class="form-input-m" inline-message>
        <el-form-item prop="questionType" label="题目类型">
          <el-select v-model="testQuestionForm.questionType" placeholder="请选择" @change="changeQuestionType" clearable :disabled='onlyShow'>
            <el-option v-for="item in questionTypeList" :key="item.code" :label="item.name" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item prop="questionContent" label="题目标题">
          <el-input type="textarea" v-model="testQuestionForm.questionContent" placeholder="请输入题目标题" v-if="testQuestionForm.questionType !== 'fill'" clearable style="width: 700px" :disabled='onlyShow'></el-input>
          <label v-if="testQuestionForm.questionType === 'fill'" style="width: 700px">{{ testQuestionForm.questionContent }}</label>
        </el-form-item>

        <div v-if="testQuestionForm.questionType === 'single' || testQuestionForm.questionType === 'multiple' || testQuestionForm.questionType === 'judge'" class="optionsConfigDiv" style="margin: 10px">
          <div class="optionCardButtons" style="margin: 0 0 10px 90px" v-if="!onlyShow">
            <el-button type="success" icon="el-icon-plus" @click="addTable">添加选项卡</el-button>
            <el-button type="danger" icon="el-icon-delete" @click="delTable">删除选项卡</el-button>
            <el-button type="warning" icon="el-icon-share" @click="cleanTable">清空选项卡</el-button>
          </div>
          <div class="dialogTableBox" style="margin: 0 0 10px 90px">
            <vxe-table ref="qiIndexMainTableRef" border align="left" class="mytable-scrollbar" :data="qiIndexIMainList" :expand-config="{ expandAll: true, reserve: true }" keep-source>
              <vxe-column type="checkbox" width="30px"></vxe-column>

              <vxe-column field="optionContent" title="选项内容">
                <template #default="scope">
                  <el-input v-if="testQuestionForm.questionType !== 'judge'" v-model="scope.row.optionContent" type="textarea" @change="changeOptionContent(scope.row)" :disabled='onlyShow'></el-input>
                  <span v-if="testQuestionForm.questionType === 'judge'">{{ scope.row.optionContent }}</span>
                </template>
              </vxe-column>

              <vxe-column field="isCorrect" title="是否正确答案" v-if="testQuestionForm.questionType === 'single' || testQuestionForm.questionType === 'multiple' || testQuestionForm.questionType === 'judge'">
                <template #default="scope">
                  <el-switch v-model="scope.row.isCorrect" inline-prompt active-text="是" inactive-text="否" @change="changeIsCorrect(scope.row)" :active-value="1" :inactive-value="0" :disabled='onlyShow'></el-switch>
                </template>
              </vxe-column>
            </vxe-table>
          </div>
        </div>

        <div v-if="testQuestionForm.questionType === 'fill'" class="optionsConfigDiv" style="margin: 10px">
          <div class="optionCardButtons" style="margin: 0 0 10px 90px" v-if="!onlyShow">
            <el-button type="success" icon="el-icon-plus" @click="addTable">添加选项卡</el-button>
            <el-button type="danger" icon="el-icon-delete" @click="delTable">删除选项卡</el-button>
            <el-button type="warning" icon="el-icon-share" @click="cleanTable">清空选项卡</el-button>
          </div>

          <el-collapse>
            <el-collapse-item title="填空题设置提示" name="1">
              <template #title>
                填空题设置提示
                <el-icon class="header-icon"><info-filled></info-filled></el-icon>
              </template>
              <p>1、选项内容请用“（）”标识填空，例：请问天空颜色是（）的？</p>
            </el-collapse-item>
          </el-collapse>
    
          <vxe-table ref="qiIndexMainTableRef" border align="left" class="mytable-scrollbar" :data="qiIndexIMainList" :expand-config="{ expandAll: true, reserve: true }" keep-source>
            <vxe-column type="checkbox" width="30px"></vxe-column>

            <vxe-column field="optionContent" title="选项内容" width="280px">
              <template #default="scope">
                <el-input v-model="scope.row.optionContent" type="textarea" @change="changeOptionContent(scope.row)" :disabled='onlyShow'></el-input>
              </template>
            </vxe-column>

            <vxe-column field="matchType" title="选择关键词匹配方式" width="120px">
              <template #default="scope">
                <el-select v-model="scope.row.matchType" placeholder="请选择" clearable :disabled='onlyShow'>
                  <el-option v-for="item in matchTypeDict" :key="item.code" :label="item.name" :value="item.code" />
                </el-select>
              </template>
            </vxe-column>

            <vxe-column field="optionKeyword" title="关键词">
              <template #default="{ row, rowIndex }">
                <div v-if='!onlyShow'>
                  <el-tag v-for="tag in dynamicTags[rowIndex]" :key="tag" closable :disable-transitions="false" @close="handleKeywordClose(row, tag, rowIndex)">
                    {{ tag }}
                  </el-tag>
                  <el-input v-if="row.inputVisible" ref="InputRef" v-model="inputValue" class="w-20" size="small" @keyup.enter="handleKeywordConfirm(row, rowIndex)" @blur="handleKeywordConfirm(row, rowIndex)" />
                  <el-button v-else class="button-new-tag" size="small" @click="showKeyword(row, rowIndex)">添加</el-button>
                </div>
                <div v-if='onlyShow'>
                  <el-tag v-for="tag in dynamicTags[rowIndex]" :key="tag">
                    {{ tag }}
                  </el-tag>
                </div>
              </template>
            </vxe-column>
          </vxe-table>
     
        </div>

        <div v-if="testQuestionForm.questionType === 'answer'" class="optionsConfigDiv" style="margin: 10px">
          <div class="optionCardButtons" style="margin: 0 0 10px 90px" v-if="!onlyShow">
            <el-button type="success" icon="el-icon-plus" @click="addTable">添加选项卡</el-button>
            <el-button type="danger" icon="el-icon-delete" @click="delTable">删除选项卡</el-button>
            <el-button type="warning" icon="el-icon-share" @click="cleanTable">清空选项卡</el-button>
          </div>
          <div class="optionCardButtons" style="margin: 0 0 10px 90px">
          <vxe-table ref="qiIndexMainTableRef" border align="left" class="mytable-scrollbar" :data="qiIndexIMainList" :expand-config="{ expandAll: true, reserve: true }" keep-source>
            <vxe-column type="checkbox" width="30px"></vxe-column>
            <vxe-column field="optionKeyword" title="关键词">
              <template #default="scope">
                <el-input v-model="scope.row.optionKeyword" type="textarea"></el-input>
              </template>
            </vxe-column>
          </vxe-table>
        </div>
        </div>
      </el-form>

      <div class="dialog-footer flex right justify-end">
        <el-button type="primary" @click="submitTestQuestion">提交</el-button>
        <el-button @click="closeTestQuestionDialog">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
// 引入组件区================
import { ref, reactive, getCurrentInstance, nextTick } from 'vue';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示
import { AppStore } from '@/stores/store';
import { ElInput } from 'element-plus';

// 定义变量区===================
let store = AppStore();
let { proxy }: any = getCurrentInstance();
const searchValue = ref('');
const searchType = ref('');
const searchQuestionTypeList = reactive([
  { code: '', name: '全部' },
  { code: 'single', name: '单项选择题' },
  { code: 'multiple', name: '多项选择题' },
  { code: 'judge', name: '判断题' },
  { code: 'fill', name: '填空题' },
  { code: 'answer', name: '简答题' }
]);

// 条数/页
const PageSizeList = [10, 50, 100, 200, 500];
let page = reactive({
  currentPage: 1,
  pageSize: 500,
  totalResult: 0
});

let testQuestionForm = reactive({
  id: null,
  questionTitle: null,
  questionType: null,
  questionContent: null,
  knowledgeId: null,
  catalogId: null,
  optionList: []
});

let TestQuestionFormRules = {};

let testQuestionList: any = reactive([]); //表格数据
let isLoading = ref(false); //表格加载状态

let showAddTestQuestionDialog = ref(false); //考题试题弹框

const qiIndexIMainList = reactive([]);

const questionTypeList = reactive([]); //题目类型选项

const qiIndexMainTableRef = ref(null); //选项卡表单

//选择关键字匹配方式选项
let matchTypeDict = reactive([
  { code: 'allWith', name: '完全包含' },
  { code: 'startWith', name: '开头包含' },
  { code: 'contains', name: '中间包含' },
  { code: 'endWith', name: '结尾包含' }
]);

const dynamicTags = reactive([]); //关键词 tab页签
const inputValue = ref(''); //关键词添加 填入input
const InputRef = ref<InstanceType<typeof ElInput>>(); //关键词添加 填入input标记

let knowledgeId: any;
let contentId: any;
let onlyShow: boolean;
let addSeq = 0;

// 方法使用区=====================
defineExpose({ initPage, findTestQuestionList, getQuestionType });

function initPage(row1: any, row2: any, row3: boolean) {
  knowledgeId = row1;
  contentId = row2;
  onlyShow = row3
}

// 获取知识库表格数据
function findTestQuestionList() {
  testQuestionList.length = 0;
  const url = '/api/wk/knowledge/test-question/page';
  proxy.$http
    .get(url, {
      params: {
        pageSize: page.pageSize,
        pageIndex: page.currentPage,
        searchValue: searchValue.value,
        searchType: searchType.value,
        knowledgeId: knowledgeId,
        catalogId: contentId
      }
    })
    .then((res: any) => {
      testQuestionList.push(...res.data.records);
      page.totalResult = res.data.total;
      addSeq = res.data.total + 1;
    })
    .catch((err: any) => {
      VxeMessage('搜索考试试题列表异常', VxeNotifyType.error);
    });
}

// 新增试题
function handleAddTest() {
  testQuestionForm.id = null;
  testQuestionForm.questionTitle = '';
  testQuestionForm.questionType = '';
  testQuestionForm.questionContent = '';
  showAddTestQuestionDialog.value = true;
  dynamicTags.length = 0; //避免 点击编辑填空题后 再点新增时回显之前填空的数据
}

// 格式化问题类型
function formatQuestionType(row) {
  // const item = questionTypeList.find((x)=> x.code === row.questionType)
  // return item.name
  if (row.questionType === 'single') {
    return '单项选择题';
  } else if (row.questionType === 'multiple') {
    return '多项选择题';
  } else if (row.questionType === 'judge') {
    return '判断题';
  } else if (row.questionType === 'fill') {
    return '填空题';
  } else if (row.questionType === 'answer') {
    return '简答题';
  }
}

// 点击编辑查询试题详情
function handleEditTest(row) {
  qiIndexIMainList.length = 0;
  const url = '/api/wk/knowledge/test-question/get/' + row.id;
  proxy.$http
    .get(url)
    .then((res: any) => {
      const item = res.data;
      testQuestionForm.id = item.id;
      testQuestionForm.questionTitle = item.questionTitle;
      testQuestionForm.questionType = item.questionType;
      testQuestionForm.questionContent = item.questionContent;
      showAddTestQuestionDialog.value = true;
      qiIndexIMainList.push(...item.optionList);

      if (item.questionType === 'fill') {
        dynamicTags.length = 0;
        for (let i = 0; i < item.optionList.length; i++) {
          dynamicTags[i] = [];
          dynamicTags[i].push(...item.optionList[i].dynamicTags);
        }
      }
    })
    .catch((err) => {
      VxeMessage('查询异常', VxeNotifyType.error);
    });

}

// 删除试题
function handleDeleteTest(row) {
  const url = '/api/wk/knowledge/test-question/delete';
  proxy.$http
    .post(url, { ids: row.id })
    .then((res: any) => {
      if (res.status.code === 1) {
        VxeMessage('删除成功', VxeNotifyType.success);
        findTestQuestionList();
      } else {
        VxeMessage('删除失败', VxeNotifyType.error);
      }
    })
    .catch((err: any) => {
      VxeMessage('删除异常', VxeNotifyType.error);
    });
}

//  切换试题类型
function changeQuestionType(typeObj: any) {
  qiIndexIMainList.length = 0;
  if (typeObj === 'single') {
    // 单项选择题
    qiIndexIMainList.push({ optionContent: '', isCorrect: 0 });
    qiIndexIMainList.push({ optionContent: '', isCorrect: 0 });
    qiIndexIMainList.push({ optionContent: '', isCorrect: 0 });
    qiIndexIMainList.push({ optionContent: '', isCorrect: 0 });
  } else if (typeObj === 'multiple') {
    // 多项选择题
    qiIndexIMainList.push({ optionContent: '', isCorrect: 0 });
    qiIndexIMainList.push({ optionContent: '', isCorrect: 0 });
    qiIndexIMainList.push({ optionContent: '', isCorrect: 0 });
    qiIndexIMainList.push({ optionContent: '', isCorrect: 0 });
  } else if (typeObj === 'judge') {
    // 判断题
    qiIndexIMainList.push({ optionContent: '正确', isCorrect: 1 });
    qiIndexIMainList.push({ optionContent: '错误', isCorrect: 0 });
  } else if (typeObj === 'fill') {
    // 填空题
    qiIndexIMainList.push({ optionContent: '', matchType: 'allWith', optionKeyword: '', inputVisible: false });
  } else if (typeObj === 'answer') {
    // 简答题
    qiIndexIMainList.push({ optionKeyword: '' });
  }
}

// 获取题目类型选项
async function getQuestionType() {
  questionTypeList.length = 0;
  let dictTreeTypeCodes: any = ['question'];
  const codes = dictTreeTypeCodes.join(',');
  const url = '/api/sys/basDictDetail/findDictDetailListByDictCodes';
  const dictTreeTypeItems: any = await proxy.$http.get(url, { params: { code: codes } });
  const horizontalType = dictTreeTypeItems.data.find((item) => item.code === 'question');
  questionTypeList.push(...horizontalType.detailDataList);
}

// 添加选项卡
function addTable() {
  let obj = { isCorrect: '0', inputVisible: false };
  qiIndexIMainList.push(obj);
}

// 删除选项卡
function delTable() {
  const selectRows = (proxy.$refs.qiIndexMainTableRef as any).getCheckboxRecords();
  if (selectRows.length <= 0) {
    VxeMessage('请勾选需要删除的数据', VxeNotifyType.warning);
    return;
  } else {
    selectRows.forEach((selectedRow) => {
      const index = qiIndexIMainList.findIndex((row) => row === selectedRow);
      if(testQuestionForm.questionType === 'fill'){
        dynamicTags[index] = []
      }
      if (index !== -1) {
        qiIndexIMainList.splice(index, 1);
      }
      testQuestionForm.questionContent = qiIndexIMainList.map((item) => item.optionContent).join('');
    });
  }
}

// 清除选项卡
function cleanTable() {
  qiIndexIMainList.length = 0;
  if(testQuestionForm.questionType === 'fill'){
    dynamicTags.length = 0
    testQuestionForm.questionContent = qiIndexIMainList.map((item) => item.optionContent).join('');
  }
}

/**
 * 提交试题表单
 */
function submitTestQuestion() {
  console.log(JSON.stringify(dynamicTags));
  proxy
    .$confirm('确定要提交？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(async () => {
      testQuestionForm.optionList.length = 0;
      testQuestionForm.optionList.push(...qiIndexIMainList);
      testQuestionForm.knowledgeId = knowledgeId;
      testQuestionForm.catalogId = contentId;
      let url = '/api/wk/knowledge/test-question/add';
      if (testQuestionForm.id !== null && testQuestionForm.id !== '' && testQuestionForm.id !== undefined) {
        url = '/api/wk/knowledge/test-question/update';
      }
      proxy.$http
        .post(url, testQuestionForm)
        .then((res: any) => {
          if (res.status.code === 1) {
            VxeMessage('保存成功', VxeNotifyType.success);
            showAddTestQuestionDialog.value = false;
            findTestQuestionList();
          } else {
            VxeMessage('保存失败', VxeNotifyType.error);
          }
        })
        .catch((err: any) => {
          VxeMessage('保存异常', VxeNotifyType.error);
        });
      // showAddTestQuestionDialog.value = false;
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}

// 弹框关闭
function closeTestQuestionDialog() {
  showAddTestQuestionDialog.value = false;
}

// 填空题设置时回显
function changeOptionContent(row) {
  if (testQuestionForm.questionType === 'fill') {
    testQuestionForm.questionContent = qiIndexIMainList.map((item) => item.optionContent).join('');
  }
}

// 填空题关键字 删除
function handleKeywordClose(row: any, tag: string, rowIndex: any) {
  if (dynamicTags[rowIndex]) {
    dynamicTags[rowIndex].splice(dynamicTags[rowIndex].indexOf(tag), 1);
    row.optionKeyword = dynamicTags[rowIndex].join(',');
  }
}

//  填空题关键字 添加
function showKeyword(row, rowIndex) {
  row.inputVisible = true;
  // 初始化 dynamicTags[rowIndex]
  if (!dynamicTags[rowIndex]) {
    dynamicTags[rowIndex] = [];
  }
  nextTick(() => {
    InputRef.value!.input!.focus();
  });
}

//  填空题关键字 回车/失去焦点 确认事件
function handleKeywordConfirm(row: any, rowIndex: any) {
  if (row.inputVisible) {
    if (!dynamicTags[rowIndex]) {
      dynamicTags[rowIndex] = [];
    }
    dynamicTags[rowIndex].push(inputValue.value);
    row.optionKeyword = dynamicTags[rowIndex].join(',');
  }
  row.inputVisible = false;
  inputValue.value = '';
}

/**
 * 单选题与多选题校验
 * @param row
 */
function changeIsCorrect(row: any) {
  const corList = qiIndexIMainList.filter((item) => item.isCorrect === 1);
  console.log(corList.length);
  if (testQuestionForm.questionType === 'single' && corList.length > 1) {
    row.isCorrect = 0;
    VxeMessage('请选择一项正确答案！', VxeNotifyType.warning);
  }
  if (testQuestionForm.questionType === 'judge' && corList.length > 1) {
    row.isCorrect = 0;
    VxeMessage('请选择一项正确答案！', VxeNotifyType.warning);
  }
}
</script>

<style lang="scss" scoped>
#knowledgeTests {
  height: 100%;
  .searchButtonDiv {
    padding: 5px;
    .vxe-input {
      margin-right: 10px;
    }
    .button-blue {
      margin: 5px 0 0 5px;
    }
  }
  .tabTableBox {
    height: calc(100% - 40px);
  }
  .dialog-footer {
    margin-top: 10px;
  }
}
</style>
